<?php
require_once ('config/connection.php');
include("resize-class.php");

$errors = array();
$data = "";
$success = "false";
$db_info = "";



function file_extension($filename)
{
    return end(explode(".", $filename));
}

if($_REQUEST['action'] == 'upload')
{

    $file_temp = $_FILES['file']['tmp_name'];
    $file_name = $_FILES['file']['name'];
    $new_name = uniqid("auto").'.'.file_extension($file_name);
    $file_path = "upload_image";
    
    if (file_extension($file_name) == "pdf")
    {
        $filestatus = move_uploaded_file($file_temp,"upload_pdf/".$new_name);
        if(!file_exists("upload_pdf/".$file_name)){
            if(!$filestatus){
                 $success = "false";
                 array_push($errors,"Upload failed. Please try again.");
            }else {
                $success = "true";
            }

  

            create_thumbnail("upload_image/pdf/pdf.png","upload_pdf/thump_pdf.jpg",50,40);
            $db_info = inserinto_database("services/upload_pdf"."/".$new_name, "services/upload_pdf/thump_pdf.jpg","services/upload_pdf/thump_pdf.jpg");
        }
        else {
            $success = "false";
            array_push($errors,"File already exists on server.");
        }
    }
    else
    {
        $filestatus = move_uploaded_file($file_temp,$file_path."/".$new_name);
        if(!file_exists($file_path."/".$file_name)) {
            if(!$filestatus) {
                 $success = "false";
                 array_push($errors,"Upload failed. Please try again.");
            } else {
                $success = "true";
            }

 $resizeObj = new resize("upload_image"."/".$new_name);

	// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
	$resizeObj -> resizeImage(600, 500, 'crop');

	// *** 3) Save image
	$resizeObj -> saveImage("upload_image"."/crop/crop_".$new_name, 100);
unset($resizeObj);

            create_thumbnail("upload_image"."/".$new_name,"upload_image"."/thumps/thump_".$new_name,50,40);
            $db_info = inserinto_database("services/upload_image"."/".$new_name, "services/upload_image"."/thumps/thump_".$new_name, "services/upload_image"."/crop/crop_".$new_name);
        } else {
            $success = "false";
            array_push($errors,"File already exists on server.");
        }
    }
	return_result($file_name, $db_info, $success, $data, $errors);
}
else if($_REQUEST['action'] == 'adminImageUpload')
{
    $file_temp_1 = $_FILES['file']['tmp_name'];
    $file_name_1 = $_FILES['file']['name'];

    $new_file_name = uniqid("user").".jpg";
    $file_path = "upload_user_image";
    
    $filestatus = move_uploaded_file($file_temp_1, $file_path."/".$new_file_name);
    if(!file_exists($file_path."/".$file_name_1)) {
        if(!$filestatus) {
             $success = "false";
             array_push($errors,"Admin Image Upload failed. Please try again.");
        } else {
            $success = "true";
        }
        create_thumbnail("upload_user_image"."/".$new_file_name,"upload_user_image"."/thumps/thump_".$new_file_name,50,40);
        $db_info = inserinto_admin_database("services/upload_user_image"."/".$new_file_name, "services/upload_user_image"."/thumps/thump_".$new_file_name);
    } else {
        $success = "false";
        array_push($errors,"File already exists on server.");
    }
	echo $success;
	//return_result($file_name_1, $db_info, $success, $data, $errors);
}
else if($_REQUEST['action'] == 'uploadAttachment')
{
	$file_temp_2 = $_FILES['file']['tmp_name'];
    $file_name_2 = $_FILES['file']['name'];
	
	$new_file_name = uniqid("attach").'.'.file_extension($file_name_2);
    $file_path = "attachments";
	
	$filestatus = move_uploaded_file($file_temp_2,"attachments/".$new_file_name);
    if(!file_exists("upload_pdf/".$file_name_2)){
        if(!$filestatus){
             $success = "false";
             array_push($errors,"Upload failed. Please try again.");
        }else {
            $success = "true";
        }
        $db_info = insertAttchToDB("services/attachments/".$new_file_name,$file_name_2 );
    }
    else {
        $success = "false";
        array_push($errors,"File already exists on server.");
    }
    attach_result($file_name_2, $db_info, $success, $data, $errors);
}
else if($_REQUEST['action'] == 'senchaUpload')
{

    $file_temp_3 = $_FILES['file']['tmp_name'];
    $file_name_3 = $_FILES['file']['name'];
    $new_name_3 = uniqid("auto").'.'.file_extension($file_name_3);
    $file_path = "upload_image";

    if (file_extension($file_name_3) == "pdf")
    {
        $filestatus = move_uploaded_file($file_temp_3,"upload_pdf/".$new_name_3);
        if(!file_exists("upload_pdf/".$file_name_3)){
            if(!$filestatus){
                 $success = "false";
                 array_push($errors,"Upload failed. Please try again.");
            }else {
                $success = "true";
            }
            create_thumbnail("upload_image/pdf/pdf.png","upload_pdf/thump_pdf.jpg",50,40);
            $db_info = inserinto_database("services/upload_pdf"."/".$new_name_3, "services/upload_pdf/thump_pdf.jpg","services/upload_pdf/thump_pdf.jpg");
        }
        else {
            $success = "false";
            array_push($errors,"File already exists on server.");
        }
    }
    else
    {
        $filestatus = move_uploaded_file($file_temp_3,$file_path."/".$new_name_3);
        if(!file_exists($file_path."/".file_temp_3)) {
            if(!$filestatus) {
                 $success = "false";
                 array_push($errors,"Upload failed. Please try again.");
            } else {
                $success = "true";
            }
$resizeObj = new resize("upload_image"."/".$new_name);

	// *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
	$resizeObj -> resizeImage(600, 500, 'crop');

	// *** 3) Save image
	$resizeObj -> saveImage("upload_image"."/crop/crop_".$new_name, 100);

            create_thumbnail("upload_image"."/".$new_name_3,"upload_image"."/thumps/thump_".$new_name_3,50,40);
            $db_info = inserinto_database("services/upload_image"."/".$new_name, "services/upload_image"."/thumps/thump_".$new_name, "services/upload_image"."/crop/crop_".$new_name);


	} else {
            $success = "false";
            array_push($errors,"File already exists on server.");
        }
    }
	echo '{success:true}';
	//sencha_upload_result($file_name_3, $db_info, $success);
}
else
{
	$success = "false";
    array_push($errors,"No action was requested.");
}
   

function create_thumbnail($infile,$outfile,$maxw,$maxh,$stretch = FALSE)
{
  clearstatcache();
  if (!is_file($infile)) {
    trigger_error("Cannot open file: $infile",E_USER_WARNING);
    return FALSE;
  }
 
  $functions = array(
    'image/png' => 'ImageCreateFromPng',
    'image/jpeg' => 'ImageCreateFromJpeg',
  );
 
  if (function_exists('ImageCreateFromGif')) { $functions['image/gif'] = 'ImageCreateFromGif'; }
 
  $size = getimagesize($infile);
 
  if (!$function = $functions[$size['mime']]) {
      trigger_error("MIME Type unsupported: {$size['mime']}",E_USER_WARNING);
    return FALSE;
  }
 
  if (!$source_img = $function($infile)) {
      trigger_error("Unable to open source file: $infile",E_USER_WARNING);
    return FALSE;
  }
 
  $save_function = "image" . strtolower(substr(strrchr($size['mime'],'/'),1));
 
  list($neww,$newh) = scale_dimensions($size[0],$size[1],$maxw,$maxh,$stretch);
 
  if ($size['mime'] == 'image/png') {
    $temp_img = imagecreatefrompng($infile);
    if (imagecolorstotal($temp_img) != 0) {
      $indexed_png = TRUE;
    } else {
      $indexed_png = FALSE;
    }
    imagedestroy($temp_img);
  }
 
  if ($size['mime'] == 'image/gif' || ($size['mime'] == 'image/png' && $indexed_png)) {
    $new_img = imagecreate($neww,$newh);
    imagepalettecopy($new_img,$source_img);
 
    $color_transparent = imagecolortransparent($source_img);
    if ($color_transparent >= 0) {
      imagefill($new_img,0,0,$color_transparent);
      imagecolortransparent($new_img, $color_transparent);
    }
  } else {
    $new_img = imagecreatetruecolor($neww,$newh);
  }
 
  imagecopyresampled($new_img,$source_img,0,0,0,0,$neww,$newh,$size[0],$size[1]);
 
  if ($save_function == 'imagejpeg') {
      if (!$save_function($new_img,$outfile,75)) {
          trigger_error("Unable to save output image",E_USER_WARNING);
          return FALSE;
      }
  } else {
      if (!$save_function($new_img,$outfile)) {
          trigger_error("Unable to save output image",E_USER_WARNING);
          return FALSE;
      }
  }
 
  imagedestroy($source_img);
  imagedestroy($new_img);
 
  return TRUE;
}

function scale_dimensions($w,$h,$maxw,$maxh,$stretch = FALSE) {
    if (!$maxw && $maxh) {
      $newh = $maxh;
      if ($h < $maxh && !$stretch) { $newh = $h; }
      else { $newh = $maxh; }
      $neww = ($w * $newh / $h);
    } elseif (!$maxh && $maxw) {
      if ($w < $maxw && !$stretch) { $neww = $w; }
      else { $neww = $maxw; }
      $newh = ($h * $neww / $w);
    } elseif (!$maxw && !$maxh) {
      return array($w,$h);
    } else {
      if ($w / $maxw > $h / $maxh) {
        if ($w < $maxw && !$stretch) { $neww = $w; }
        else { $neww = $maxw; }
        $newh = ($h * $neww / $w);
      } elseif ($w / $maxw <= $h / $maxh) {
        if ($h < $maxh && !$stretch) { $newh = $h; }
        else { $newh = $maxh; }
        $neww = ($w * $newh / $h);
      }
    }
    return array(round($neww),round($newh));
}

function inserinto_database($filestr, $thumpstr, $cropstr)
{
    $lastResult;
    $vehID = $_REQUEST['vehicleID'];
    $my_insert = "INSERT INTO vehicle_image (  `image_url` , `vehicle_id`, `thump_url`, `crop_url`  ) VALUES ('".$filestr. "',".$vehID.",'" .$thumpstr. "','".$cropstr."')";  
$my_insert = mysql_query($my_insert) or die("Query ERROR");
    $result_sel = mysql_insert_id();
    $lastResult->imageUrl = $filestr;
    $lastResult->thumpUrl = $thumpstr;
$lastResult->corpUrl = $cropstr;

    $lastResult->imageID = $result_sel;
    $lastResult->vehID = $vehID;
    /*$up_type = $_REQUEST['upload_type'];
    if($my_insert && $up_type='seller')
    {
        $my_select = "SELECT email,first_name FROM vehicle WHERE vehicle_id=".$vehID;
        $my_select = mysql_query($my_select) or die("Query ERROR");
        $row = mysql_fetch_object($my_select);
    
        $_instance = new VehicleService();
        $messages = 'Seller added new picture';
        $colName ='update_date';
        $reply ='New picture uploaded';
        $vehicleVO = $_instance->updateMessageVehicleID($messages, $colName, $reply, false, NULL);
    }*/
    return $lastResult;

}

function insertAttchToDB($server, $orginal)
{
    $lastResult;
    $myDate = date('Y-m-d H:i:s');
    $commentID = $_REQUEST['commentID'];
    $my_insert_1 = "INSERT INTO attachments ( `org_file_name` , `server_file_name`, `date`  ) VALUES ('".$orginal."','".$server."','" .$myDate. "')";
    $my_insert = mysql_query($my_insert_1) or die("Query ERROR".$my_insert_1);
    $result_sel = mysql_insert_id();
    $lastResult->org_file_name = $server;
    $lastResult->server_file_name = $orginal;
    $lastResult->attachID = $result_sel;
    return $lastResult;
}

function return_result($imagename, $info, $success, $data, $errors)
{
    $result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    $result .= "<results>\n";
    $result .= "<success>".$success."</success>";
    $result .= "<imagename>".$imagename."</imagename>";
    $result .= "<imageid>".$info->imageID."</imageid>";
    $result .= "<imageUrl>".$info->imageUrl."</imageUrl>";
    $result .= "<thumpUrl>".$info->thumpUrl."</thumpUrl>";
    $result .= "<corpUrl>".$info->corpUrl."</corpUrl>";
    $result .= "<vehicleId>".$info->vehID."</vehicleId>";
    $result .=    $data;
    for($i=0;$i<count($errors);$i++)
    {
        $result .= "<error>".$errors[$i]."</error>";
    }
    $result .=    "</results>";
    
    echo($result);
}

function attach_result($imagename, $info, $success, $data, $errors)
{
    $result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    $result .= "<results>\n";
    $result .= "<success>".$success."</success>";
    $result .= "<orgName>".$imagename."</orgName>";
    $result .= "<serverName>".$info->server_file_name."</serverName>";
    $result .= "<attachID>".$info->attachID."</attachID>";
    $result .=   $data;
    for($i=0;$i<count($errors);$i++)
    {
        $result .= "<error>".$errors[$i]."</error>";
    }
    $result .=    "</results>";
    
    echo($result);
}

function sencha_upload_result($imagename, $info, $success, $data, $errors)
{
    /*$result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    $result .= "<results>\n";
    $result .= "<success>".$success."</success>";
    $result .= "<orgName>".$imagename."</orgName>";
    $result .= "<serverName>".$info->server_file_name."</serverName>";
    $result .= "<attachID>".$info->attachID."</attachID>";
    $result .=   $data;
    for($i=0;$i<count($errors);$i++)
    {
        $result .= "<error>".$errors[$i]."</error>";
    }
    $result .=    "</results>";
    echo($result);*/
}

function inserinto_admin_database($filestr, $thumpstr)
{
    $adminID = $_REQUEST['admin_id'];
    $my_insert = "UPDATE user_master SET `image_url` ='".$filestr."',`image_thump`='".$thumpstr."' WHERE user_id=".$adminID;
    $my_insert_1 = mysql_query($my_insert) or die("Query ERROR".$my_insert);
    return $my_insert_1;
}
?>
